package com.wft.ohters;

import java.util.Random;

public class TestThread {
    public static void main(String[] args) {
        Man man = new Man();
        Productor p1 = new Productor(man);
        Consumer c1 = new Consumer(man);
        new Thread(p1).start();
        new Thread(c1).start();
//        new Thread(p1).start();
    }
}

class Man{
    int product = 0;


    public synchronized void toConsume() {
        if(product <= 0){
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }else {
            System.out.println(Thread.currentThread().getName() + "==>consume==>" + product);
            product--;
            notifyAll();
        }
    }

    public synchronized void toProduct() {
        if(product >= 20){
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }else {
            product++;
            System.out.println(Thread.currentThread().getName() + "==>product==>" + product);
            notifyAll();
        }
    }
}

class Productor implements Runnable{
    private Man man;

    public Productor(Man man) {
        this.man = man;
    }

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep((long) (Math.random() * 1000));
            } catch (InterruptedException e) {
            }
            man.toProduct();
        }
    }
}


class Consumer implements Runnable{
    private Man man;

    public Consumer(Man man) {
        this.man = man;
    }

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep((long) (Math.random() * 1000));
            } catch (InterruptedException e) {
            }
            man.toConsume();
        }
    }
}